#include "seqiot.h"
#include "sqlite.h"
#include "value.h"

void sqlite_post_check(char *err, sqlite3 *db) {
    int errcode = sqlite3_errcode(db);
    const char *errmsg = sqlite3_errmsg(db);
    log_error("[0x%08x] %s", errcode, errmsg);
    strcpy(err, errmsg);
}

void sqlite_check(sqlite3 *db) {
    int errcode = sqlite3_errcode(db);
    const char *errmsg = sqlite3_errmsg(db);
    log_error("[0x%08x] %s", errcode, errmsg);
}

sqlite3 *sqlite_open(const char *filename) {
    sqlite3 *db = NULL;

    if (SQLITE_OK != sqlite3_open_v2(filename, &db, SQLITE_OPEN_READWRITE, NULL)) {
        sqlite_check(db);
        return NULL;
    }

    return db;
}

sqlite3 *sqlite_open_read(const char *filename) {
    sqlite3 *db = NULL;

    if (SQLITE_OK != sqlite3_open_v2(filename, &db, SQLITE_OPEN_READONLY, NULL)) {
        sqlite_check(db);
        return NULL;
    }

    return db;
}

void read_row_str(sqlite3_stmt *stmt, int iCol, char *to, size_t size) {
    const unsigned char *str = sqlite3_column_text(stmt, iCol);
    if (NULL != str) {
        bzero(to, size);
        strncpy(to, str, size - 1);
    } else {
        to[0] = '\0';
    }
}

void read_row_object(sqlite3_stmt *stmt, object_t *rs) {
    rs->id = sqlite3_column_int(stmt, 0);
    read_row_str(stmt, 1, rs->name, sizeof(rs->name));
}